﻿@using System.Web.Configuration
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


    <div id="add-edit-dialog" style="display: none" title="Add / Edit Job Post"> 
        <form id="add-edit-form">
        <div id="messageBox1">
            <ul></ul> 
        </div>
	   <fieldset>
           <legend></legend>
           <input type="hidden" name="itemid" id="itemid" />
		    <label for="role">Role</label>
		    <input type="text" name="role" id="role" class="text ui-widget-content ui-corner-all" />
		    <label for="description">Description</label>
            <textarea id="description" name="description" cols="32" rows="3" class="ui-widget-content" ></textarea>		
		    <label for="jobtype">Job Type</label>
		    <input type="text" name="jobtype" id="jobtype" value="" class="text ui-widget-content ui-corner-all" />
            <label for="paymentrate">Payment Rate</label>
		    <input type="text" name="paymentrate" id="paymentrate" value="" class="text ui-widget-content ui-corner-all" />
            <label for="location">Location</label>
		    <input type="text" name="location" id="location" value="" class="text ui-widget-content ui-corner-all" />
	   </fieldset>
            </form>
    </div>


<br />
<table id="jobListing" style="display: none"></table>

@section Styles {
    <style>
		input.text { margin-bottom:12px; width:95%; padding: .4em; }
		fieldset { padding:0; border:0; margin-top:25px; }
		h1 { font-size: 1.2em; margin: .6em 0; }
		.ui-dialog .ui-state-error { padding: .3em; }        
        .error {
         border-color:red !important;
         border-style:solid;
         border-width:1px;
        }
        label.error {
            border: none;
        }
        		
	</style>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/flexigrid")

    <script type="text/javascript">
        var jobPost = {
            Id: null,
            Role: null,
            Location: null,
            JobType: null,
            Description: null,
            setVals: function (id, role, location, jobtype, description) {
                this.Id = id;
                this.Role = role;
                this.Location = location;
                this.JobType = jobtype;
                this.Description = description;
            }
        };
        var txtId = $("#itemid");
        var txtRole = $("#role");
        var txtLocation = $("#location");
        var txtJobType = $("#jobtype");
        var txtDescription = $("#description");

        //http://groups.google.com/group/flexigrid
        $('#jobListing').flexigrid({
            url: '@(WebConfigurationManager.AppSettings["VirtualDir"])/Jobs/List',
            dataType: 'json',
            colModel: [
                {
                display: 'Role',
                name: 'Role',
                width: 180,
                sortable: true,
                align: 'left'
            },{
                display: 'Description',
                name: 'Description',
                width: 180,
                sortable: true,
                align: 'left'
            },{
                display: 'Job Type',
                name: 'JobType',
                width: 130,
                sortable: true,
                align: 'left'
            },{
                display: 'Location',
                name: 'Location',
                width: 120,
                sortable: true,
                align: 'left'
            }],
            buttons: [{
                name: 'Add',
                bclass: 'add',
                onpress: test
            }, {
                name: 'Edit',
                bclass: 'edit',
                onpress: test
            }, {
                name: 'Delete',
                bclass: 'delete',
                onpress: test
            }, {
                separator: true
            }],
            searchitems: [{
                display: 'Role',
                name: 'Role'
            }, {
                display: 'Location',
                name: 'Location',
                isdefault: true
            }],
            sortname: "Role",
            sortorder: "asc",
            usepager: true,
            title: 'Job Listing',
            useRp: true,
            rp: 15,
            showTableToggleBtn: true,
            width: 700,
            height: 200
        });

        function test(com, grid) {
            var selectedRows = $('.trSelected', grid).length;
            
            if (com == 'Edit' && selectedRows > 0) {
                if (selectedRows == 1) {
                    
                    $('.trSelected', grid).each(function () {                        
                        setFormControls($(this).attr('id').substr(3),
                            $('td[abbr="Role"] >div', this).html(),
                            $('td[abbr="Location"] >div', this).html(),
                            $('td[abbr="JobType"] >div', this).html(),
                            $('td[abbr="Description"] >div', this).html());
                    });

                    $("#add-edit-dialog").dialog("open");
                } else {
                    alert("Select only one row");
                }                
            }
            else if (com == 'Delete' && selectedRows > 0) {
                var proceed = confirm('Delete ' + selectedRows + ' item(s)?');
                
                if (!proceed) {
                    return false;
                }

                var ids = new Array();
                
                $('.trSelected', grid).each(function (index) {
                    ids[index] = $(this).attr('id').substr(3);
                });
                
                $.ajax({
                    type: 'POST',
                    data: JSON.stringify(ids),
                    url: '@(WebConfigurationManager.AppSettings["VirtualDir"])/Jobs/Delete',
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (result) {
                        // insert new list into grid
                        $('#jobListing').flexAddData(result);
                    }
                });
                
            } else if (com == 'Add') {
                $("#add-edit-dialog").dialog("open");
            }
        }
        
        function setFormControls(id, role, location, jobtype, description) {
            txtId.val(id);
            txtRole.val(role);
            txtLocation.val(location);
            txtJobType.val(jobtype);
            txtDescription.val(description);
        }

        $(document).ready(function(){
            
            // See the second answer: http://stackoverflow.com/questions/4453072/jquery-ui-dialog-with-form-validation-plugin 
            
            // Use the provided links to implement validate method for displaying errors
            // http://www.mail-archive.com/jquery-en@googlegroups.com/msg70120.html
            // http://justinribeiro.com/chronicle/2009/10/02/jquery-ui-modal-form-with-validation-and-form-plugin-integration/

            var validator = $("#add-edit-form").validate({
                errorContainer: "#messageBox1",
                errorLabelContainer: "#messageBox1 ul",
                wrapper: "li",
                rules: {
                    'role': { required: true },
                    'description': { required: true },
                    'location': { required: true }
                },
                messages: {
                    'role': "The Role field is required",
                    'description': "The Description field is required",
                    'location': "The Location field is required"
                }
            });

            $("#add-edit-dialog").dialog({
                autoOpen: false,
                height: 500,
                width: 380,
                modal: true,
                buttons: {
                    "Save": function () {
                        
                        if ($("#add-edit-form").valid()) {
                            jobPost.setVals(txtId.val(), txtRole.val(), txtLocation.val(), txtJobType.val(), txtDescription.val());                            

                            $.ajax({
                                type: 'POST',
                                data: JSON.stringify(jobPost),
                                url: '@(WebConfigurationManager.AppSettings["VirtualDir"])/Jobs/Save',
                                dataType: 'json',
                                contentType: 'application/json',
                                success: function (result) {
                                    // insert new list into grid
                                    $('#jobListing').flexAddData(result);
                                }
                            });
                            $(this).dialog('close');
                        } else return false;
                        
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                        validator.resetForm();
                    }
                },
                close: function () { setFormControls('', '', '', '', ''); },
                open: function () {
                    //$("#add-edit-dialog").parent().appendTo($("#add-edit-form"));
                }
            });
        });


	</script>

}
